package com.hitqz.robot.driver.zmq.protocol.component;

import com.hitqz.robot.driver.zmq.protocol.message.ProtocolMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class ZMQObservableImpl implements ZMQObservable {

    List<Class<?>> handlerServers = new ArrayList<>();


    List<Class<?>> eventNotifyServers = new ArrayList<>();

    public ZMQObservableImpl() {
        handlerServers = new ArrayList<>();
    }

    @Override
    public void addObserver(Class<?> server) {
        handlerServers.add(server);
    }

    @Override
    public void deleteObserver(Class<?> server) {
        if (!handlerServers.isEmpty()) {
            handlerServers.remove(server);
        }
    }

    @Override
    @Async
    public void notifyObserver(String address,String type, byte[] data) {
        ProtocolMessage receiveData = new ProtocolMessage(address,type,data);
        for (Class<?> server : handlerServers) {
            try{
                Method method = server.getDeclaredMethod("receive", ProtocolMessage.class);
                method.invoke(server.newInstance(), receiveData);
            } catch (Exception e) {
                log.error("[wheel][zmq]notifyObserver: receive data error : " , e);
            }
        }
    }

    @Override
    public void notifyMoniterTask() {

    }

}
